package com.antoco.operation.bigscreen.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.regex.Pattern;

/**
 * <p>Title: StringUtil</p>
 * <p>Description:TODO</p>
 * <p>Company: 69</p>
 *
 * @author cuidd
 * @date 2013-8-2
 */
public class StringUtil extends StringUtils {
  /**
   * 把一个字符串中连续的几个空格替换成一个@，字符串前后各添一个@
   *
   * @param str
   * @return
   */
  public static String getString(String str) {
    String newBlankList = "";
    try {
        String[] black = str.split(" ");
        for (int i = 0; i < black.length; i++) {
            String subString = black[i];
            if (" ".equals(subString) || "".equals(subString)) {
                continue;
            }
            newBlankList += "@" + subString.trim();
        }
        newBlankList += "@";
    } catch (Exception e) {
        e.printStackTrace();
    }
    return newBlankList;
  }


  public static String compressContent(String content, int len) {
    String s = null;
    if (!StringUtil.isEmpty(content)) {
        s = content.replaceAll("</?[^>]+>", "").replace("\r", "")
                .replace("\\s+", "").replace("\t", "").replace("\n", "")
                .replace("&nbsp;", "");
        if (s.length() > len) {
            return s = s.substring(0, len);
        }
    }
    return s;
  }


  /**
   * 用于List界面的字符串截取显示(字节方式截取)
   *
   * @param str    字符串
   * @param length 截取长度，字节
   * @param addDot 截取后字符串是否加点
   * @return
   */
  public static String byteSubstring(String str, int length, boolean addDot) {
    if (isEmpty(str)) {
        return "";
    }

    byte[] b = str.getBytes();

    // 加3个点的长度
    if (addDot) {
        length -= 3;
    }

    if (b.length <= length) {
        return str;
    }

    try {
        str = bSubstring(str, length);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return addDot ? str + "..." : str;
  }

  /**
   * <p>
   * Title: encode
   * </p>
   * <p>
   * Description:TODO
   * </p>
   *
   * @param s
   * @return String
   * @author cuidd
   * @date 2013-8-2
   * @version 1.0
   */
  public static String encode(String s) {
    String str = null;
    if (!isEmpty(s)) {
        try {
            str = URLEncoder.encode(s, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
    return str;
  }


  /**
   * <p>
   * Title: decode
   * </p>
   * <p>
   * Description:TODO
   * </p>
   *
   * @param s
   * @return String
   * @author cuidd
   * @date 2013-8-2
   * @version 1.0
   */
  public static String decode(String s) {
    String str = null;
    if (!isEmpty(s)) {
        try {
            str = URLDecoder.decode(s, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
    return str;
  }

  /**
   * <p>
   * Title: bSubstring
   * </p>
   * <p>
   * Description:TODO
   * </p>
   *
   * @param s
   * @param length
   * @return String
   * @throws Exception
   * @author cuidd
   * @date 2013-7-10
   * @version 1.0
   */
  public static String bSubstring(String s, int length) throws Exception {
    byte[] bytes = s.getBytes("Unicode");
    int n = 0; // 表示当前的字节数
    int i = 2; // 要截取的字节数，从第3个字节开始
    for (; i < bytes.length && n < length; i++) {
        // 奇数位置，如3、5、7等，为UCS2编码中两个字节的第二个字节
        if (i % 2 == 1) {
            n++; // 在UCS2第二个字节时n加1
        } else {
            // 当UCS2编码的第一个字节不等于0时，该UCS2字符为汉字，一个汉字算两个字节
            if (bytes[i] != 0) {
                n++;
            }
        }
    }
    // 如果i为奇数时，处理成偶数
    if (i % 2 == 1) {
        // 该UCS2字符是汉字时，去掉这个截一半的汉字
        if (bytes[i - 1] != 0) {
            i = i - 1;
            // 该UCS2字符是字母或数字，则保留该字符
        } else {
            i = i + 1;
        }
    }

    return new String(bytes, 0, i, "Unicode");
  }

    /**
     * 检查传入的参数是否为JSON
     *
     * @param jsonInString
     * @return
     */
    public final static boolean isJson(String jsonInString ) {
        try {
            final ObjectMapper mapper = new ObjectMapper();
            mapper.readTree(jsonInString);
            return true;
        } catch (IOException e) {
            return false;
        }
    }

    /**
     * 去除前侧指定字符
     * @param source
     * @param beTrim
     * @return
     */
    public static String ltrim(String source, String beTrim) {
      return trimStr(source, beTrim, "left", true);
    }

    /**
     * 去除后侧指定字符
     * @param source
     * @param beTrim
     * @return
     */
    public static String rtrim(String source, String beTrim) {
        return trimStr(source, beTrim, "left", true);
    }

    /**
     * 去除前后指定字符
     * @param source
     * @param beTrim
     * @return
     */
    public static String trim(String source, String beTrim) {
        return trimStr(source, beTrim, "both", true);
    }

    /**
     * 去除前后指定字符
     * @param source 目标字符串
     * @param beTrim 要删除的指定字符
     * @return 删除之后的字符串
     */
    public static String trimStr(String source, String beTrim, String type, boolean trimSpace) {
        if(source == null){
            return "";
        }

        // 去除前后空格
        source = trimSpace ? source.trim() : source;

        // 参数检查
        if(source.isEmpty() || beTrim == null || beTrim == ""){
            return source;
        }

        // 循环去掉前面
        if (type == "left" || type == "both") {
            while (source.indexOf(beTrim) == 0) {
                source = source.substring(beTrim.length());
            }
        }

        // 循环去掉后面
        if (type == "right" || type == "both") {
            while (source.endsWith(beTrim)) {
                source = source.substring(0, source.length() - beTrim.length());
            }
        }

        return source;
    }

    /**
     * 转换数据库表明为类名：详细参照同名重载函数
     */
    public static String convertTableName2ClassName(String tableName, Boolean isFirstLetterUpper) {
        return convertTableName2ClassName(tableName, isFirstLetterUpper, "t_", "_");
    }

    /**
     * 用一下规则转换数据库表明为类名
     *
     * ・去除表名前缀
     *
     *
     * @param tableName
     * @return
     */
    public static String convertTableName2ClassName(String tableName, Boolean isFirstLetterUpper, String prefix, String delimiter) {
        if (tableName == null || tableName.trim() == "") {
            return "";
        }

        // 去除两边空格
        tableName = tableName.trim();

        // 去除表前缀
        tableName = ltrim(tableName, prefix);

        // 切割并生成类名
        StringBuilder className = new StringBuilder();
        String[] tableNameItems = tableName.split(delimiter);
        for (String item : tableNameItems) {
            className.append(toFirstLetterUpperCase(item));
        }

        if (isFirstLetterUpper) {
            return className.toString();
        } else {
            return toFirstLetterLowerCase(className.toString());
        }
    }

    /**
     * 转换字符串为首字母小写
     *
     * @param source
     * @return
     */
    public static String toFirstLetterLowerCase(String source) {
        if (source == null || source.trim() == "" || Character.isLowerCase(source.charAt(0))) {
            return source;
        } else {
            return (new StringBuilder())
                    .append(Character.toLowerCase(source.charAt(0)))
                    .append(source.substring(1))
                    .toString();
        }
    }

    /**
     * 转换字符串为首字母小写
     *
     * @param source
     * @return
     */
    public static String toFirstLetterUpperCase(String source) {
        if (source == null || source.trim() == "" || Character.isUpperCase(source.charAt(0))) {
            return source;
        } else {
            return (new StringBuilder())
                    .append(Character.toUpperCase(source.charAt(0)))
                    .append(source.substring(1))
                    .toString();
        }
    }

    /**
     * 判断字符串是否为数字
     * @param str
     * @return
     */
    public static boolean isNumeric(String str){
        Pattern pattern = Pattern.compile("[0-9]*");
        return pattern.matcher(str).matches();
    }
}
